package net.xdclass.coupon.message.listener;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.common.message.MessageInfo;
import net.xdclass.coupon.service.CouponRecordService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * mq 消息消费者，用来判断订单状态，决定是否释放优惠券
 */
@Slf4j
@Component
@RabbitListener(queues = "${mqconfig.coupon_release_queue}")
public class CouponMqListener {

    @Autowired
    private CouponRecordService couponRecordService;

    @RabbitHandler
    public void onMessage(MessageInfo messageInfo, Message msg, Channel channel){
        log.info("消息消费者接收消息：【{}】", messageInfo);
        long deliveryTag = msg.getMessageProperties().getDeliveryTag();
        boolean success = couponRecordService.releaseCouponRecord(messageInfo);
        try {
            if (success) {
                channel.basicAck(deliveryTag, false);
            }else {
                channel.basicReject(deliveryTag, true);
                log.warn("消息消费失败，重新入队。【{}】", messageInfo);
            }
        } catch (IOException e) {
            try {
                channel.basicReject(deliveryTag, true);
                log.warn("消息消费异常，重新入队。【{}】", messageInfo);
            } catch (IOException ex) {
            }
        }
    }

}
